<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<title>群聊天室</title>
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link href="../css/iconfont.css" rel="stylesheet" />
		<link href="../css/websocket.css" rel="stylesheet" />

	</head>
	<body style="background-color: rgb(44, 45, 46);">
		<header class="mui-bar mui-bar-nav title-header noshadow" style="background-color: #000000;">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left title-color title-size-left"></a>
			<h1 id="groupName-header" class="mui-title title-color"></h1>
			<a id="goGroupInfo" class="mui-pull-right mui-icon iconfont icon-group title-color"></a>
		</header>
		<div class="mui-scroll-wrapper" style="margin-top:44px;height:88vh;background-color: rgb(44, 45, 46);">
			<div class="mui-scroll">
				<div id='message' style="color: #FFFFFF;">
				



				</div>
			</div>
		</div>
		
		<footer style="height:6vh;position: absolute; z-index: 99; ">
			<div class="footer-center">
				<textarea id='msg-text' type="text" maxlength="200" class='input-text'></textarea>
			</div>
			<label for="" class="footer-right margin-right">
				<button type="button" class="mui-btn mui-btn-gray send-btn" id="send-text">发送</button>
			</label>
		</footer>
		
		<div id="modal2" class="modalDIY mui-hidden">
			<div class="bg">
				<div class="modalTitle">
					<div class="header_img">
						<img id="headerImg" onerror="javascript:this.src='../images/nickname.png'" src="../images/nickname.png" style="border-radius: 360px;" width="100px" height="100px"/>
					</div>
					</div> 
				<div id="modalContent" class="modalContent modalMessage">
					<p class="txt">账号：<span id="openid">Na</span></p>
					<p class="txt">昵称： <span id="nickname">Mr.chen</span></p> 
					<p class="txt">最高分：<span id="maxscore">100</span></p>
					<slot></slot>
				</div>
				<div class="modalOperate">
					<div id="_resetbtn" class="comfirmBtn">确认</div>
				</div>
			</div>
		</div> 
		<script src="../js/mui.min.js"></script>
		<script src="../js/app.js"></script>
		<script src="../js/config.js"></script>
		<script src="../js/template-web.js"></script>
		<script type="text/javascript">
			mui.plusReady(function() {

				mui('.mui-scroll-wrapper').scroll({
					scrollY: true, //是否竖向滚动
					scrollX: false, //是否横向滚动
					startX: 0, //初始化时滚动至x
					startY: 0, //初始化时滚动至y
					indicators: true, //是否显示滚动条
					deceleration: 0.0006, //阻尼系数,系数越小滑动越灵敏
					bounce: true //是否启用回弹
				});
				var webSocket;
				if (window.WebSocket) {
					webSocket = new WebSocket(app.getWebSocketUrl());
				} else {
					alert("抱歉，您的浏览器不支持WebSocket协议!");
				}

				//连通之后的回调事件
				webSocket.onopen = function() {
					console.log("已经连通了websocket");
					var openid = app.getUserInfo().userOpenId;
					//进入频道 默认1
					var map = new Map();
					map.set("type", "init");
					map.set("userOpenId", openid);
					map.set("room", 1);
					var message = Map2Json(map);
					console.log("message:" + message);
					webSocket.send(message);
					var message = document.getElementById("message");
					var msgList = [];
					getRedisMessageList(1,app.getUserInfo().token, function(data) {
						if (data) {
							msgList = data;
							return;
						}
					});
					
					for(var i=0;i<msgList.length;i++) {
						setMessageInnerHTML(msgList[i]);
					}
				}
				//连接发生错误的回调方法
				webSocket.onerror = function(event) {
					console.log("出错了");
					//              setMessageInnerHTML("连接失败");
				};

				//连接关闭的回调方法
				webSocket.onclose = function() {
					console.log("连接已关闭...");

				}

				//接收到消息的回调方法
				webSocket.onmessage = function(event) {
					console.log("bbdds");
					var data = JSON.parse(event.data)
					switch (data.type) {
						case 'init':
							console.log("mmll");
							break;
						case 'msg':
							console.log("bblld");
							setMessageInnerHTML(data);
							break;
						default:
							break;
					}
				}
				
				function enter() {
					var map = new Map();
					var nick = document.getElementById('nick').value;
					var room = document.getElementById('room').value;
					map.set("type", "init");
					map.set("userOpenId", nick);
					console.log(room);
					map.set("room", room);
					var message = Map2Json(map);
					console.log("message:" + message);
					webSocket.send(message);
				}

				var send = document.getElementById('send-text');
				send.addEventListener('click', function() {
					var msgText = document.getElementById('msg-text');
					var msg = msgText.value;
						
					console.log("1:" + msg);
					if (msg != null && msg != "") {
						var map = new Map();
						map.set("type", "msg");
						map.set("msg", msg);
						var map2json = Map2Json(map);
						console.log("map2json:" + map2json);
						if (map2json.length < 8000) {
							console.log("4:" + map2json);
							webSocket.send(map2json);
							msgText.value = "";
						} else {
							console.log("文本太长了，少写一点吧😭");
						}
					}
				});
				var date = null;
				//将消息显示在网页上
				function setMessageInnerHTML(data) {

					var message = document.getElementById("message");
					openid = app.getUserInfo().userOpenId;
					var innerHTML = "";
					var nowdate = new Date();
					nowdate = nowdate.toLocaleDateString() +"/"+ nowdate.getHours();
					var msgdate = new Date(data.sendDateTime);
					
					if(msgdate == "Invalid Date") {
						msgdate = new Date();
					}
					msgdate = msgdate.toLocaleDateString() +"/"+ msgdate.getHours();
					console.log(msgdate);
					if(msgdate != date) {
						let time = new Date(data.sendDateTime).toLocaleString()
						if(time === 'Invalid Date') {
							time = new Date().toLocaleString()
						}
						let htmlstr = '<p style="text-align: center;">'+ time +'</p>';
						innerHTML = innerHTML + htmlstr;
						
						date = msgdate;
					}
					
					//右边
					if (openid === data.userOpenId) {
						let htmlstr = template('msgRightTemplate', data);
						innerHTML = innerHTML + htmlstr;
					} else {
						let htmlstr = template('msgLeftTemplate', data);
						innerHTML = innerHTML + htmlstr;
					}
					message.innerHTML += innerHTML;
					var height = document.documentElement.clientHeight;
					if (message.scrollHeight > (height * 0.87)) {
						mui('.mui-scroll-wrapper').scroll().scrollTo(0, -message.scrollHeight + height * 0.87);
					}


				}

				function Map2Json(map) {
					var str = "{";
					map.forEach(function(value, key) {
						str += '"' + key + '"' + ':' + '"' + value + '",';
					})
					str = str.substring(0, str.length - 1)
					str += "}";
					return str;
				}
			});
			
			
			
			var modal = document.getElementById('modal2');
			mui("#message").on('tap', '.datalist', function() {
				var openid = this.getAttribute('data-openid');
				var img = this.getAttribute('data-img');
				var nickname = this.getAttribute('data-nickname');
				var score = this.getAttribute('data-score');
				document.getElementById('headerImg').src = img;
				document.getElementById('openid').innerText = openid;
				document.getElementById('nickname').innerText = nickname;
				document.getElementById('maxscore').innerText = score;
				console.log()
				modal.classList.remove('mui-hidden');
				
			});
			var _resetbtn = document.getElementById('_resetbtn');
			_resetbtn.addEventListener('click',function(){
				modal.classList.add('mui-hidden');
			})
		</script>
		<script type="text/template" id="msgLeftTemplate">
			<div class="friend_lists">
				<div class="header_img datalist" data-img={{userAvatarUrl}} data-openid={{userOpenId}} data-nickname={{userNickName}} data-score={{maxScore}}>
					<img onerror="javascript:this.src='../images/nickname.png'" src="{{userAvatarUrl}}" width="40px" height="40px"/>
				</div>
				<div class="msg-wrapper right">
					<p class="msg-left-white">{{msg}}</p>
				</div>
			</div>
		</script>
		<script type="text/template" id="msgRightTemplate">
			<div class="me_lists">
				<div class="header_img datalist"  data-img={{userAvatarUrl}} data-openid={{userOpenId}} data-nickname={{userNickName}} data-score={{maxScore}}>
					<img onerror="javascript:this.src='../images/nickname.png'" src="{{userAvatarUrl}}" width="40px" height="40px"/>
				</div>
				<div class="msg-wrapper left">
					<p class="msg-right-green">{{msg}}</p>
				</div>
			</div>
		</script>

		<script type="text/template" id="imageLeftTemplate">
			<div class="friend_lists">
			<div class="header_img">
				<img src="{{avatarPrefix}}{{person.faceImageCut}}" width="40px" height="40px" onclick="goUserInfo('{{person.id}}')"/>
			</div>
			<div class="msg-wrapper right">
				<p class="msg-left-white" onclick="goImageDetail('{{imageSrc}}')">
					<img src="{{imageSrc}}"  width="80" height="80"/>
				</p>
			</div>
		</div>
	</script>
		<script type="text/template" id="imageRightTemplate">
			<div class="me_lists">
			<div class="header_img">
				<img src="{{avatarPrefix}}{{person.faceImageCut}}" width="40px" height="40px" onclick="goUserInfo('{{person.id}}')"/>
			</div>
			<div class="msg-wrapper left">
				<p class="msg-right-green" onclick="goImageDetail('{{imageSrc}}')">
					<img src="{{imageSrc}}"  width="80" height="80"/>
				</p>
			</div>
		</div>
	</script>
	</body>
</html>
